<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Circle;
use App\Models\Comment;
use App\Models\Label;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CircleController extends Controller
{
    public function index(Request $request)
    {
        $limit = $request->get('limit', 20);

        $label_id = $request->get('label_id');

        /**
         * 一对多关联，label_ids结构是json格式的字符串
         * FIXME：用foreach循环处理，也许会有更好的方法
         */
        $data = Circle::query()->select('id', 'user_id', 'label_ids', 'star', 'content', 'images', 'created_at')->orderByDesc('id')->where(function ($queue) use ($label_id) {
            if ($label_id) {
                //$queue->whereRaw('JSON_CONTAINS(label_ids,' . $label_id . ')');
                $queue->where('label_ids', 'like', '%'.$label_id . '%');
            }
        })->paginate($limit);

        foreach ($data->items() as &$item) {
            $item['label_ids'] = json_decode($item['label_ids'], true);
            $item['label'] = Label::query()->whereIn('id', $item['label_ids'])->pluck('title');
            $images = json_decode($item['images'], true);

            //处理图片路径 返回给前端绝对路径
            foreach ($images as $key => $value) {
                $images[$key] = asset($value);
            }
            $item['images'] = $images;
            unset($item['label_ids']);
        }

        return $this->success($data);
    }

    public function destroy($ids)
    {
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {

            Circle::query()->whereIn('id', $ids)->delete();
            //删除底下的评论
            Comment::query()->whereIn('circle_id', $ids)->delete();
            DB::commit();
        }catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    public function getLabel()
    {
        $data = Label::all('id', 'title');
        return $this->success($data);
    }

    public function getCircleComment($id)
    {
        $data = Comment::query()->where('circle_id', $id)->get();

        $data = self::tree($data);

        return $this->success($data);
    }

    /**
     * 递归
     * @param $data
     * @param int $pid
     * @return array
     */
    private static function tree($data, $pid = 0)
    {
        $res = array();

        foreach ($data as $key => $value) {
            if ($value['pid'] == $pid) {
                $res[] = $value;
                $res = array_merge($res, self::tree($data, $value['id']));
            }
        }
        return $res;
    }
}
